<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/28 14:05
 * Modified Time: 2019/6/28 14:05
 * Version: 2.0
 */

namespace App\Modules\Store\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Lib\Auth\FLAuth;
use App\Lib\CreateStaticNumber;
use App\Lib\Utilities;
use App\Modules\Store\Repositories\RenewalRepository;
use App\Modules\Store\Repositories\RenewalSettingRepository;
use App\Modules\Store\Repositories\StoreRenewalRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use App\Modules\Employee\Repositories\EmployeeRepository;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use mysql_xdevapi\Exception;

class RenewalService extends BaseService
{
    private $employeeRepository;
    private $renewalRepository;
    private $renewalSettingRepository;
    private $storeRenewalRepository;

    public function __construct(
        EmployeeRepository $employeeRepository,
        RenewalRepository $renewalRepository,
        RenewalSettingRepository $renewalSettingRepository,
        StoreRenewalRepository $storeRenewalRepository)
    {
        $this->employeeRepository = $employeeRepository;
        $this->renewalRepository = $renewalRepository;
        $this->renewalSettingRepository = $renewalSettingRepository;
        $this->storeRenewalRepository = $storeRenewalRepository;
    }

    /*
     * 获取续费规则
     */
    public function getRenewalRule($user_id, $store_id)
    {
        $rule = $this
            ->renewalSettingRepository
            ->getRenewalSetting($user_id, $store_id)
            ->rule;
        $rule = json_decode($rule);
        $return_data = [];
        foreach ($rule[0] as $key => $value){
            $return_data[] = [
                'years'=>$key,
                'price'=>$value
            ];
        }
        return $return_data;
    }

    /**
     * 获取剩余服务天数
     */
    public function getServiceRemainingDays($user_id, $store_id)
    {
        return $this
            ->renewalSettingRepository
            ->getServiceRemainingDays($user_id, $store_id);
    }
    /*
     * 支付宝提交订单
     */
    public function renewalAlipay($user_id,$total_amount,$years)
    {
        $user = $this->employeeRepository->findByField(['id'=>$user_id])->first();
        $renewal_id = $user->renewal_id;

        //创建订单号

        $renewal_no = CreateStaticNumber::makeNo('fee');


        //创建订单
        $renewal_order = $this->storeRenewalRepository->createStoreRenewal($user_id,$renewal_id,$years,$total_amount,0,$renewal_no);

        $order = [
            'out_trade_no' => $renewal_order->id,
            'total_amount' => $total_amount,
            'subject' => 'test subject - 测试',
            'years' => $years,
            'user_id' => $user_id,
            'renewal_id' => $renewal_id,
            'renewal_no' => $renewal_no,
        ];
        return $order;
    }

    /*
     * 支付宝验签
     */
    public function notifyAlipay($trade_status,$out_trade_no,$total_amount,$app_id)
    {
        // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
        // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
        // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
        // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
        // 4、验证app_id是否为该商户本身。
        // 5、其它业务逻辑情况

        if($trade_status !== 'TRADE_SUCCESS' && $trade_status !== 'TRADE_FINISHED'){
            throw new AllValidatorException(['msg'=>'支付失败']);
        }

        if($app_id != config('alipay.app_id')){
            throw new AllValidatorException(['msg'=>'app_id错误']);
        }

        //获取未支付订单实例
        $renewal_order = $this->storeRenewalRepository->getStoreRenewalByNo($out_trade_no);

        if($total_amount != $renewal_order->price){
            throw new AllValidatorException(['msg'=>'支付金额错误']);
        }

        DB::beginTransaction();
        try{

            //加时间
            $this->addYears($renewal_order);

            //改订单状态
            $this->storeRenewalRepository->update(['status'=>1],$renewal_order->id);

            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            throw new DbException();
        }

    }

    /*
     * 续费加时间
     */
    private function addYears($renewal_order)
    {
        $user_id = $renewal_order->user_id;
        $years = $renewal_order->years;

        //续费后的到期时间戳
        $user = $this->employeeRepository->findByField(['id'=>$user_id])->first();

        $time = $user->expire + ($years * 31536000);

        $this->employeeRepository->update(['expire'=>$time],$user_id);

    }
}